package com.dhgate.spu.analysis.stat;

import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.FacetField;
import org.apache.solr.client.solrj.response.FacetField.Count;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;

import com.dhgate.spu.analysis.bean.SpuStandard;
import com.dhgate.spu.analysis.consts.CommonConsts;
import com.dhgate.spu.analysis.consts.SpuStandardConsts;
import com.dhgate.spu.analysis.consts.SysConsts;
import com.dhgate.spu.analysis.init.InitDbConfig;
import com.dhgate.spu.analysis.init.InitParameter;
import com.dhgate.spu.analysis.util.StringUtil;

/**
 * @author: 
 * @create: 2014-2-15 下午3:29:26
 * @description:
 */
public class StatMain {
	public static long SPU_NUMBER = 1;
	public static void main(String[] args) throws Exception {
		// 初始化基本配置参数
		InitParameter.init();
		// 读取数据库初始化配置
		InitDbConfig.init();
		SpuStandardConsts.init();
		if(args.length<1){
			throw new Exception("input prodlineid is null");
		}

		doStat(args[0]);
	}

	private static void doStat(String prodLineId) throws SolrServerException {
		SolrQuery statSolrQuery = new SolrQuery();
		List<SpuStandard> spuStandList = SpuStandardConsts.getSpuStandList(prodLineId);
		if(spuStandList == null || spuStandList.size() == 0){
			System.err.println(" not get spuStandList by prodLineId:"+prodLineId);
			return;
		}
		
		int spuNum = 0;
		long itemNum = 0;
		long spuItemNum = 0;
		long haveOneItemSpuNum = 0;
		long spuHaveMaxItemNum = 0;
	
		
		SolrQuery solrQuery = new SolrQuery();
		solrQuery.setQuery("prodlineid:"+prodLineId);
		QueryResponse qr = SysConsts.SOLR_SERVER.query(solrQuery);
		itemNum = qr.getResults().getNumFound();
		
		List<List<String>> spuUniqueKeyList = new ArrayList<List<String>>();
		for(SpuStandard spuStand : spuStandList){
			List<String> subSpuUniqueKeyList = new ArrayList<String>();
			statSolrQuery.clear();
			spuUniqueKeyList.add(subSpuUniqueKeyList);
			statSolrQuery.setQuery("*:*");
			statSolrQuery.addFilterQuery("prodlineid:"+prodLineId);
			statSolrQuery.setRows(0);
			statSolrQuery.setFacetMinCount(1);
			statSolrQuery.setFacetLimit(50000);
			statSolrQuery.setFacet(true);
			statSolrQuery.addFilterQuery(CommonConsts.ExtFieldName.SPU_STANDARD_ID+":"+spuStand.getId());
			statSolrQuery.addFacetField(CommonConsts.ExtFieldName.SPU_UNIQUE_KEY);
			qr = SysConsts.SOLR_SERVER.query(statSolrQuery);
			FacetField ff = qr.getFacetField(CommonConsts.ExtFieldName.SPU_UNIQUE_KEY);
			for (Count count : ff.getValues()) {
				long lcount = count.getCount();
				if (lcount == 1) {
					haveOneItemSpuNum++;
				}
				spuItemNum = spuItemNum + count.getCount();
				spuHaveMaxItemNum = lcount > spuHaveMaxItemNum ? lcount : spuHaveMaxItemNum;
				subSpuUniqueKeyList.add(count.getName());
				spuNum++;
			}
		}
		
		
		statSolrQuery.clear();
		statSolrQuery.setQuery("*:*");
		statSolrQuery.setRows((int) spuHaveMaxItemNum);
		statSolrQuery.setFields("itemcode");
		

		System.out.println("SPU数量：                        " + spuNum);
		System.out.println("SPU覆盖产品百分比：      " + spuItemNum * 100.0f / itemNum + "%");
		System.out.println("SPU平均包含产品数：      " + spuItemNum / spuNum);
		System.out.println("SPU率：                           " + spuNum*100.0f / spuItemNum + "%");
		System.out.println("-只有一个产品的SPU数：" + haveOneItemSpuNum + " 占SPU比:" + haveOneItemSpuNum * 100.0f / spuNum + "%");
		System.out.println("-总产品数：                      " + itemNum);
		System.out.println("-spu覆盖到的产品数：    " + spuItemNum);
		
		for(int i=0; i<spuUniqueKeyList.size(); i++ ){
			 List<String> uniqueKeyList = spuUniqueKeyList.get(i);
			 System.out.println("=====>SpuStandard"+(i+1)+getSpuStandardInfo(spuStandList.get(i),prodLineId));
			 for(String spuUniqueKey : uniqueKeyList){
				 printSpu(spuUniqueKey, statSolrQuery,spuStandList.get(i).getExtFieldList(),prodLineId);
			 }
		}
	}
	
	private static void printSpu(String spuUniqueKey, SolrQuery statSolrQuery, List<String> extFieldNameList,String prodLineId) throws SolrServerException{
		statSolrQuery.setFilterQueries(CommonConsts.ExtFieldName.SPU_UNIQUE_KEY+":\""+spuUniqueKey+"\"");
		statSolrQuery.addFilterQuery("prodlineid:"+prodLineId);
		QueryResponse qr = SysConsts.SOLR_SERVER.query(statSolrQuery);
		long haveItemNum = qr.getResults().getNumFound();
		StringBuffer icSB = new StringBuffer();
		for (SolrDocument doc : qr.getResults()) {
			icSB.append(doc.get("itemcode")).append(",");
		}
		
		//attrId1:attrVal1,attrVal2;attrId2:attrVal1,attrVal2|extfiled1,extfiled2
		String uniqueKeyArray[] = spuUniqueKey.split("\\|");
		String attrUniqueKey = null;
		String extFiledUniqueKey = null;
		String keywords=null;
		if(uniqueKeyArray.length>0){
			for(String key:uniqueKeyArray){
					if(key.startsWith("attrs")){
						attrUniqueKey=key.replaceFirst("attrs ", "");
					}else if(key.startsWith("ExtFields")){
						extFiledUniqueKey=key.replaceFirst("ExtFields ", "");
					}else if(key.startsWith("keywords")){
						keywords=key.replaceFirst("keywords ", "");
					}
			}
		}
		StringBuffer spuInfoSB = new StringBuffer();
		if(StringUtil.isNotEmpty(attrUniqueKey)){
			for(String attr : attrUniqueKey.split(";")){//attrId1:attrVal1,attrVal2
				String attrId = attr.split(":")[0];//attrId1
				String attrValIdArray[] = attr.split(":")[1].split(",");//attrVal1,attrVal2
				spuInfoSB.append(SpuStandardConsts.getAttrEnName(prodLineId, attrId+"")+":");
				int length = attrValIdArray.length;
				for(int i=0; i<length; i++){
//					spuInfoSB.append(AttrConsts.PHONE_ATTR_VAL_ID_2_ATTR_VAL_ENNAME_MAP.get(attrValIdArray[i]));
					spuInfoSB.append(SpuStandardConsts.getAttrValEnName(prodLineId, attrValIdArray[i].trim()));
					if(i<(length-1)){
						spuInfoSB.append(",");
					}
				}
				spuInfoSB.append(";");
			}
		}
		
		String spuValue = "";
		if(spuInfoSB.length() > 0){
			spuValue = spuInfoSB.substring(0,spuInfoSB.length()-1);
		}
		
		if(StringUtil.isNotEmpty(extFiledUniqueKey)){
			String[] extFieldValueArray = extFiledUniqueKey.split(",");
			spuValue = spuValue + "|ExtFields ";
			for(int i=0;i<extFieldNameList.size();i++){
				spuValue = spuValue + extFieldNameList.get(i)+":"+extFieldValueArray[i]+";";
			}
		}
		if(StringUtil.isNotEmpty(keywords)){
			spuValue+="|keywords "+keywords;
		}
		
		if(spuValue.endsWith(";")){
			spuValue = spuValue.substring(0,spuValue.length()-1);
		}
		
		System.out.println("spu" + SPU_NUMBER + " | spu内容: ["+spuValue+"]" + " | 产品数量:" + haveItemNum + " | itemcodes:(" + icSB.substring(0, icSB.length() - 1) + ")");
		SPU_NUMBER++;
	}
	
	private static String getSpuStandardInfo(SpuStandard spuStand,String prodLineId){
		StringBuffer spuStandInfoSB = new StringBuffer();
		if(spuStand.getAttrIdList() != null && spuStand.getAttrIdList().size()>0){
			spuStandInfoSB.append(" attrs:");
			for(Long attrId : spuStand.getAttrIdList()){
				spuStandInfoSB.append(SpuStandardConsts.getAttrEnName(prodLineId, attrId+""));
			}
			spuStandInfoSB = new StringBuffer(spuStandInfoSB.substring(0,spuStandInfoSB.length()-1));
		}
		
		if(spuStand.getExtFieldList() != null && spuStand.getExtFieldList().size() > 0){
			spuStandInfoSB.append(" | ExtFileds: ");
			for(String extField : spuStand.getExtFieldList()){
				spuStandInfoSB.append(extField+",");
			}
			
		}
		if(spuStand.getExtractKeyword()!=null&&spuStand.getExtractKeyword().getSourceFieldNames()!=null){
			spuStandInfoSB.append(" | keywords: ");
			for(String s:spuStand.getExtractKeyword().getSourceFieldNames()){
				spuStandInfoSB.append(s+",");
			}
		}
		
		String spuStandInfo = spuStandInfoSB.toString();
		return spuStandInfo.endsWith(",") ? spuStandInfo.substring(0,spuStandInfo.length()-1) : spuStandInfo;
	}

}
